#!/usr/bin/env python
#coding=utf-8
#Simple HTTP Server With Upload.
#This module builds on BaseHTTPServer by implementing the standard GET
#and HEAD requests in a fairly straightforward manner.

import os
import sys
import time
import datetime
import getopt
import json
from socket import *
#from http.server import HTTPServer,BaseHTTPRequestHandler
from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
import ssl
from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer

import io,shutil  
import urllib

E2_TYPE="payload_inspections"
E3_TYPE="sample_inspections"
policy_path="./"
e2_full_path = policy_path + E2_TYPE
e3_full_path = policy_path + E3_TYPE
other_full_path = policy_path + "other"
CUSTOM_PATH_KEY="Rule-Path"

def isSubstr(s1,s2):
    return s1 in s2    
class Request(BaseHTTPRequestHandler):
    def do_POST(self):
        print ("----------REQUEST----------");
        print ("POST %s" % self.path);
        print (self.headers);
        custom_path_val = self.headers.get(CUSTOM_PATH_KEY)
        length = int(self.headers.getheader('content-length'))
        qs = self.rfile.read(length)
        print (qs);

        # send response message
        print ("----------RESPONSE----------");
        self.send_response(200)
        self.send_header('Content-type', 'application/json')
        self.send_header('Content-Length', '37')
        self.end_headers()
        #resp_dict = {'key':'hello', 'password':'world'}
        #resp_str=json.dumps(resp_dict, sort_keys=False)
        #self.wfile.write(resp_str.encode())
        resp_str = "PROCESSED SUCCESS"
        self.wfile.write(resp_str)
        # write to local file
        ts = int(time.time())
        plcType = self.path.split('/')
        plcType = self.path[1:]
        plcId = "0"
        if isSubstr(E2_TYPE, plcType) :
            plcId = "11"
            subpath = e2_full_path
        elif isSubstr(E3_TYPE, plcType) :
            plcId = "12"
            subpath = e3_full_path
        else:
            plcId = "0"
            subpath = other_full_path

        if custom_path_val != None:
            filepath = policy_path +  custom_path_val
            print ("====filepath2:%s" % filepath)
            if  not os.path.exists(filepath):
                os.makedirs(filepath)
            filename = filepath + "/11_" + E2_TYPE + "_" + str(ts) + '.txt'
            print ("====filename2:%s" % filename)
        else :
            filename = subpath + "/" + plcId + "_" + plcType + "_" + str(ts) + '.xml'
            print ("filename1=%s" % filename)

        with open(filename, 'w') as fs:
            fs.write(qs + "\n")
        #self.wfile.write(json.dumps('Traffic data is inserted').encode())
        #self.wfile.write('这里用来传数据')
        # 下面的形式可以用来传html文件
        # with open('D:\\Python网络编程基础\\Python代码\\http.html','rb') as t:
        #   print('输出了')
        #   self.wfile.write(t.read())
        print ("----------RESPONSE END----------");
    def do_GET(self):
        print ("----------REQUEST----------");
        print ("GET:%s" % self.path);
        self.outputtxt(self.path)
        print ("----------RESPONSE END----------");
     
    def outputtxt(self, content):
        enc = "UTF-8"
        content = content.encode(enc)          
        f = io.BytesIO()
        f.write(content)
        f.seek(0)  
        self.send_response(200)  
        self.send_header("Content-type", "text/html; charset=%s" % enc)  
        self.send_header("Content-Length", str(len(content)))  
        self.end_headers()  
        shutil.copyfileobj(f,self.wfile)    
def run(Host, Port):
    host=Host
    port=Port
    #
    print('Listening on %s:%s' % (host,port))
    #server=HTTPServer((host,port),Request)
    server=HTTPServer((host, port), Request)
    server.socket = ssl.wrap_socket(server.socket, certfile='server.pem', server_side=True)

    #serve_forever
    server.serve_forever()

def init():
    if  not os.path.exists(e2_full_path):
        os.makedirs(e2_full_path)
    if not  os.path.exists(e3_full_path):
        os.makedirs(e3_full_path)

if __name__=='__main__':
    opts, args = getopt.getopt(sys.argv[1:], "hs:p:", ["help", "server=", "port="])
    #print("[*] Params: ", opts)
    ParamHost = '127.0.0.1'
    ParamPort = 443
    for opt_name,opt_val in opts:
        if opt_name in ('-h'):
            print ("[*] Usage: python3 http_client.py -s http://10.10.90.46:9000/IDCWebService/ -f <file>")
            sys.exit()
        if opt_name in ('-s', '--server'):
            ParamHost = opt_val
            print ("[*] Param: -s ", ParamHost)
        if opt_name in ('-p', '--port'):
            ParamPort = int(opt_val)
            print ("[*] Param: -p ", ParamPort)
            break
        # print(Request.path)
    init()
    time.sleep(1)
    if ParamPort < 1:
        print ("[*]: input param error, no port is defined");
        sys.exit()
    run(ParamHost, ParamPort)
